<template>
  <div class="false-positive-management">
    <!-- Tab 标签页 -->
    <el-tabs v-model="activeTab" class="management-tabs">
      <!-- 误报 Tab -->
      <el-tab-pane label="误报" name="false-positive">
        <!-- 统计卡片区 -->
        <el-row :gutter="20" class="stats-card-row">
          <el-col :span="6" v-for="(stat, index) in statsData" :key="index">
            <el-card class="stat-card" :class="stat.class">
              <div class="stat-title">{{ stat.title }}</div>
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-desc">{{ stat.desc }}</div>
            </el-card>
          </el-col>
        </el-row>
        <FalsePositiveList
          ref="listRef"
          @refresh="handleListRefresh"
          @submit="showSubmitDialog = true"
          @analysis="showAnalysisDialog = true"
          @view-detail="handleViewDetail"
          @confirm="handleConfirm"
          @reject="handleReject"
          @ignore="handleIgnore"
          @recover="handleRecover"
          @add-whitelist="handleAddWhitelist"
          @batch-confirm="handleBatchConfirm"
          @batch-ignore="handleBatchIgnore"
          @batch-whitelist="handleBatchWhitelist"
        />
      </el-tab-pane>

      <!-- 白名单 Tab -->
      <el-tab-pane label="白名单" name="whitelist">
        <WhitelistManagement />
      </el-tab-pane>
    </el-tabs>

    <!-- 对话框组件 -->
    <FalsePositiveDetailDialog
      v-model="showDetailDialog"
      :detail-id="currentDetailId"
      :detail-data="detailData"
      :loading="detailLoading"
      @refresh-list="handleListRefresh"
      @confirm="handleConfirm"
      @reject="handleReject"
      @ignore="handleIgnore"
      @add-whitelist="handleAddWhitelist"
    />
    <SubmitFalsePositiveDialog
      v-model="showSubmitDialog"
      @refresh-list="handleListRefresh"
    />
    <!-- <WhitelistManagementDialog v-model="showWhitelistDialog" /> -->
    <!-- <FalsePositiveAnalysisDialog v-model="showAnalysisDialog" /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
// 引入API
import {
  getFalsePositiveStatistics,
  getFalsePositiveDetail,
  submitFalsePositive,
  confirmFalsePositive,
  rejectFalsePositive,
  ignoreFalsePositive,
} from "../../servers";
import { useUserStoreHook } from "@/store/modules/user";
// 引入组件
import FalsePositiveList from "./components/pagelist.vue";
import FalsePositiveDetailDialog from "./components/FalsePositiveDetailDialog.vue";
import SubmitFalsePositiveDialog from "./components/SubmitFalsePositiveDialog.vue";
import WhitelistManagement from "./WhitelistManagement/index.vue";

// 状态管理
const statsData = ref<
  Array<{
    title: string;
    value: string;
    desc: string;
    class: string;
  }>
>([
  {
    title: "待处理",
    value: "0",
    desc: "条需要处理的误报",
    class: "pending-stat",
  },
  {
    title: "已确认",
    value: "0",
    desc: "条确认的误报",
    class: "confirmed-stat",
  },
  { title: "已忽略", value: "0", desc: "条忽略的误报", class: "ignored-stat" },
  { title: "误报率", value: "0%", desc: "总体误报比例", class: "rate-stat" },
]);

// 组件引用
const listRef = ref<InstanceType<typeof FalsePositiveList>>();

// Tab 状态
const activeTab = ref("false-positive");

// 对话框状态
const showDetailDialog = ref(false);
const showSubmitDialog = ref(false);
const showWhitelistDialog = ref(false);
const showAnalysisDialog = ref(false);
const currentDetailId = ref("");
const detailData = ref<any>({});
const detailLoading = ref(false);

// 页面初始化
onMounted(() => {
  fetchStatistics();
});

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await getFalsePositiveStatistics();

    const stats = response.data?.data || response.data;
    if (
      stats &&
      (stats.pending_count !== undefined || stats.confirmed_count !== undefined)
    ) {
      statsData.value = [
        {
          title: "待处理",
          value: (stats.pending_count || 0).toString(),
          desc: "条需要处理的误报",
          class: "pending-stat",
        },
        {
          title: "已确认",
          value: (stats.confirmed_count || 0).toLocaleString(),
          desc: "条确认的误报",
          class: "confirmed-stat",
        },
        {
          title: "已忽略",
          value: (stats.ignored_count || 0).toString(),
          desc: "条忽略的误报",
          class: "ignored-stat",
        },
        {
          title: "误报率",
          value: `${(stats.false_positive_rate || 0).toFixed(2)}%`,
          desc: "总体误报比例",
          class: "rate-stat",
        },
      ];
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
    ElMessage.error(error.message || "获取统计数据失败");
  }
};

// 列表刷新
const handleListRefresh = () => {
  fetchStatistics();
};

// 获取详情数据
const fetchDetailData = async (id: string | number) => {
  if (!id) return;

  detailLoading.value = true;
  try {
    const { data } = await getFalsePositiveDetail({ id: Number(id) });

    // const data = response.data.data;

    // 转换数据类型，确保数值字段是数字类型
    if (data.risk_detail) {
      if (typeof data.risk_detail.original_score === "string") {
        data.risk_detail.original_score =
          parseFloat(data.risk_detail.original_score) || 0;
      }
      if (typeof data.risk_detail.deduction === "string") {
        data.risk_detail.deduction =
          parseFloat(data.risk_detail.deduction) || 0;
      }
    }

    if (
      data.reason_info &&
      typeof data.reason_info.score_adjustment === "string"
    ) {
      data.reason_info.score_adjustment =
        parseFloat(data.reason_info.score_adjustment) || 0;
    }

    if (typeof data.processing_hours === "string") {
      data.processing_hours = parseFloat(data.processing_hours) || null;
    }

    detailData.value = data;
  } catch (error: any) {
    console.error("获取详情失败:", error);
    ElMessage.error(error.message || "获取详情失败");
    detailData.value = {};
  } finally {
    detailLoading.value = false;
  }
};

// 查看详情
const handleViewDetail = async (row: any) => {
  currentDetailId.value = row.id;
  await fetchDetailData(row.id);
  showDetailDialog.value = true;
};

// 确认误报
const handleConfirm = async (data?: { id?: string | number; row?: any }) => {
  const id = data?.id || (data?.row ? data.row.id : null);
  if (!id) {
    ElMessage.warning("缺少误报记录ID");
    return;
  }

  try {
    await confirmFalsePositive({
      id: Number(id),
      reviewed_by: useUserStoreHook()?.username || "system",
    });

    ElMessage.success("误报确认成功");
    listRef.value?.fetchList();
    fetchStatistics();
    // 刷新详情数据
    if (id) {
      await fetchDetailData(id);
    }
  } catch (error: any) {
    ElMessage.error(error.message || "确认失败");
  }
};

// 拒绝误报
const handleReject = async (data?: { id?: string | number; row?: any }) => {
  const id = data?.id || (data?.row ? data.row.id : null);
  if (!id) {
    ElMessage.warning("缺少误报记录ID");
    return;
  }

  try {
    await rejectFalsePositive({
      id: Number(id),
      reviewed_by: useUserStoreHook()?.username || "system",
      reject_reason: "经核实，该风险确实存在，不是误报",
    });

    ElMessage.success("误报已拒绝");
    listRef.value?.fetchList();
    fetchStatistics();
    // 关闭详情对话框
    if (showDetailDialog.value) {
      showDetailDialog.value = false;
    }
  } catch (error: any) {
    ElMessage.error(error.message || "拒绝失败");
  }
};

// 忽略误报
const handleIgnore = async (data?: { id?: string | number; row?: any }) => {
  const id = data?.id || (data?.row ? data.row.id : null);
  if (!id) {
    ElMessage.warning("缺少误报记录ID");
    return;
  }

  try {
    await ignoreFalsePositive({
      id: Number(id),
      ignored_by: useUserStoreHook()?.username || "system",
      ignore_reason: "暂时忽略，待后续处理",
    });

    ElMessage.success("误报已忽略");
    listRef.value?.fetchList();
    fetchStatistics();
    // 关闭详情对话框
    if (showDetailDialog.value) {
      showDetailDialog.value = false;
    }
  } catch (error: any) {
    ElMessage.error(error.message || "忽略失败");
  }
};

// 恢复误报
const handleRecover = (row: any) => {
  // TODO: 实现恢复逻辑
  ElMessage.info("恢复功能待实现");
  listRef.value?.fetchList();
  fetchStatistics();
};

// 加入白名单
const handleAddWhitelist = (data?: { id?: string | number; row?: any }) => {
  const row = data?.row || (data?.id ? { id: data.id } : null);
  if (!row) {
    ElMessage.warning("缺少误报记录信息");
    return;
  }

  // 切换到白名单标签页，提示用户手动创建白名单规则
  activeTab.value = "whitelist";
  ElMessage.info("请在白名单页面创建相应的白名单规则");
};

// 批量确认
const handleBatchConfirm = async (rows: any[]) => {
  if (!rows || rows.length === 0) {
    ElMessage.warning("请选择要操作的记录");
    return;
  }

  try {
    const promises = rows
      .filter((row) => row.status_type === "pending")
      .map((row) =>
        confirmFalsePositive({
          id: Number(row.id),
          reviewed_by: useUserStoreHook()?.username || "system",
        })
      );

    await Promise.all(promises);
    ElMessage.success(`成功确认 ${promises.length} 条误报记录`);
    listRef.value?.fetchList();
    fetchStatistics();
  } catch (error: any) {
    ElMessage.error(error.message || "批量确认失败");
  }
};

// 批量忽略
const handleBatchIgnore = async (rows: any[]) => {
  if (!rows || rows.length === 0) {
    ElMessage.warning("请选择要操作的记录");
    return;
  }

  try {
    const promises = rows
      .filter((row) => row.status_type === "pending")
      .map((row) =>
        ignoreFalsePositive({
          id: Number(row.id),
          ignored_by: useUserStoreHook()?.username || "system",
          ignore_reason: "批量忽略",
        })
      );

    await Promise.all(promises);
    ElMessage.success(`成功忽略 ${promises.length} 条误报记录`);
    listRef.value?.fetchList();
    fetchStatistics();
  } catch (error: any) {
    ElMessage.error(error.message || "批量忽略失败");
  }
};

// 批量加入白名单
const handleBatchWhitelist = (rows: any[]) => {
  if (!rows || rows.length === 0) {
    ElMessage.warning("请选择要操作的记录");
    return;
  }

  // 切换到白名单标签页，提示用户手动创建白名单规则
  activeTab.value = "whitelist";
  ElMessage.info(
    `已选择 ${rows.length} 条记录，请在白名单页面创建相应的白名单规则`
  );
};
</script>

<style scoped lang="scss">
.false-positive-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
}

.user-info {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #666;
  font-size: 14px;
}

.stats-card-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
  padding: 15px;
  border-radius: 6px;
  transition: all 0.3s;
  cursor: pointer;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }
}

.stat-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
}

.stat-desc {
  color: #999;
  font-size: 12px;
}

.pending-stat {
  border-left: 4px solid #1890ff;

  .stat-value {
    color: #1890ff;
  }
}

.confirmed-stat {
  border-left: 4px solid #52c41a;

  .stat-value {
    color: #52c41a;
  }
}

.ignored-stat {
  border-left: 4px solid #faad14;

  .stat-value {
    color: #faad14;
  }
}

.rate-stat {
  border-left: 4px solid #f5222d;

  .stat-value {
    color: #f5222d;
  }
}

.management-tabs {
  // margin-top: 20px;

  :deep(.el-tabs__header) {
    margin-bottom: 20px;
  }

  :deep(.el-tabs__item) {
    font-size: 16px;
    font-weight: 500;
  }
}

.whitelist-placeholder {
  padding: 100px 20px;
  text-align: center;
  background-color: #fff;
  border-radius: 8px;
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
